require('../../../../less/back/rent/rent.less');
import $ from 'jQuery';
var map = null;
var drawingManager =null;
var operateParam={}; //操作参数，区分新增和更新
var titleList = [];
var titleArr=[];
(function () {
    let orderData = JSON.parse(IOT.getSessionStore(URI.RENT.TRACKING.SET_RANGE.PAGE));
    let $vue = new Vue({
        el: '.client-rang-detail-hook',
        methods: {
            cancleBack: function () {
                M.Page.emitPrePage();
                // M.Page.emitRefreshPage();
            },
            addNewRange:function(){
                layer.open({
                    type: 1,
                    title: '新增围栏',
                    shadeClose: true,
                    resize: false,
                    shade: 0.4,
                    area: ['400px', '200px'],
                    skin: 'layui-layer-rim',
                    btn: ['确定','取消'],
                    content: $('#modal-dialog'),
                    yes:function(){   //确定按钮执行

                        if($('#range_title').val() ==''){
                            IOT.tips('请输入围栏名称！', 'error', 1000, null);
                            return;
                        }
                        for (var i=0;i<titleList.length;i++) {
                            if (titleList[i].indexOf($.trim($('#range_title').val())) > -1) {
                                IOT.tips('该围栏名称已存在，请重新输入！', 'error', 1000, null);
                                return;
                            }
                        }
                        if($('#range_title').val().trim()){
                            operateParam={
                                businessNo: orderData.transportBillNo,
                                fenceName: $('#range_title').val().trim()
                            };
                            layer.closeAll();//会清空表单
                            drawingManager.open();
                        }else{
                            IOT.tips('请设置围栏名称！', 'error', 1000, null);
                            return;
                        }
                    },
                    no:function(){
                        $('#range_title').val('');
                    },
                    success: function () {   //弹窗开始前执行
                        $('#range_title').val('');
                        operateParam={};
                        clearMap();
                    },end:function(){      //弹窗结束前执行
                        $('#range_title').val('');
                    }
                })
            },
            updateRange:function(row){
                layer.open({
                    type: 1,
                    title: '编辑围栏',
                    shadeClose: true,
                    resize: false,
                    shade: 0.4,
                    area: ['400px', '200px'],
                    skin: 'layui-layer-rim',
                    btn: ['确定','取消'],
                    content: $('#modal-dialog'),
                    yes:function(){    //确定执行
                       titleArr=titleList;
                       titleArr.remove(row.fenceName);
                        if($('#range_title').val() ==''){
                            IOT.tips('请输入围栏名称！', 'error', 1000, null);
                            return;
                        }
                        for (var i=0;i<titleArr.length;i++) {
                            if (titleArr[i].indexOf($.trim($('#range_title').val())) > -1) {
                                IOT.tips('该围栏名称已存在，请重新输入！', 'error', 1000, null);
                                return;
                            }
                        }
                        if($('#range_title').val().trim()){
                            operateParam={
                                businessNo: orderData.transportBillNo,
                                fenceName: $('#range_title').val().trim(),
                                fenceId: row.fenceId
                            };
                            layer.closeAll();
                            layer.confirm('请问是否需要重绘围栏？', {
                                btn: ['是','否']
                            }, function(){
                                layer.closeAll();
                                clearMap();
                                drawingManager.open();
                            }, function(){
                                //设置参数-围栏数据
                                operateParam.drawData = row.drawData;
                                updateFence(operateParam);
                                clearMap();
                                showElecFenceVal(JSON.parse(operateParam.drawData));
                                operateParam={};
                            });
                        }else{
                            IOT.tips('请设置围栏名称！', 'error', 1000, null);
                            return;
                        }
                    },
                    success: function () {      //弹窗开始前执行
                        $('#range_title').val(row.fenceName);
                        operateParam={};
                    },end:function(){           //弹窗结束前执行
                        $('#range_title').val('');
                    }
                });
            }
        },
        mounted:function(){
            this.$nextTick(() => {
                var $accountBox = $('.set_range-table-hook');
                let $form = $('.form-search-range');
                // 查询
                $('.search-hook').on('click', function () {
                    $($accountBox).bootstrapTable('onCustomSearch');
                });
                var $tableHook = $accountBox.bootstrapTable({
                    scrollbar: 'set_range-table-body',
                    striped: true, // 设置为 true 会有隔行变色效果
                    pagination: true, // true 显示分页
                    paginationDetail: false, // 分页详情
                    sidePagination: 'server', // 服务器端
                    pageList:'All',
                    method: 'post',
                    url: URI.RENT.TRACKING.ELETIC_RANGE.LIST,
                    debug: false,
                    cache: false,
                    pageNumber: 1,
                    pageSize: 10,
                    // fixedColumns: true,
                    customButton: '',
                    customQueryParams: function (params) {
                        let formParams = $form.serializeJson();
                        formParams.businessNo = orderData.transportBillNo;
                        let queryParams = $.extend({}, params, formParams);
                        return queryParams;
                    },
                    onLoadSuccess: function (data) {
                        $.each(data.rows,function(i,v){
                            titleList.push(v.fenceName);
                        })
                    },
                    columns: [
                        {
                            field: 'fenceName', title: '围栏名称', align: 'center', fixedLeft: true,
                            events: {
                                'click .show-fence': function (e, value, row, index) {
                                    clearMap();
                                    var _distributerange = JSON.parse(row.drawData);
                                    showElecFenceVal(_distributerange);
                                }
                            },
                            formatter: function (value, row, index) {
                                return '<a class="show-fence">'+value+'</a>';
                            }

                        },
                        {
                            field: 'operate', title: '操作', align: 'center', fixedLeft: true,width:100,
                            events: {
                                'click .modify-account': function (e, value, row, index) {
                                    $vue.updateRange(row);
                                },
                                'click .delete-account': function (e, value, row, index) {
                                    layer.confirm('确定删除该围栏设置？', {
                                        btn: ['确定','取消'] //按钮
                                    }, function(){
                                        deleteFence({fenceId: row.fenceId});
                                    }, function(){
                                    });
                                }
                            },
                            formatter: function (value, row, index) {
                                let html = [];
                                if (M.Authority.checkAuthority('pallet-track-fence-edit')) {
                                    html.push('<a class="operate modify-account">编辑</a>');
                                }
                                if (M.Authority.checkAuthority('pallet-track-fence-delete')) {
                                    html.push('<a class="operate delete-account">删除</a>');
                                }
                                return html.join('');

                            }
                        }
                    ]
                });
                // 查看
                if (!M.Authority.checkAuthority('pallet-track-fence-edit') && !M.Authority.checkAuthority('pallet-track-fence-delete')) {
                    $tableHook.bootstrapTable('hideColumn', 'operate'); // 隐藏列
                }
            })

        }
    });
})();

/**
 * 初始化地图
 */
var initMap = function(){
    map =new BMap.Map("set_range_map");    // 创建Map实例
    var point = new BMap.Point(118.783, 32.050);  // 创建点坐标
    map.centerAndZoom(point, 15); //初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl({isOpen: true}));
    //实例化鼠标绘制工具
    drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingMode:BMAP_DRAWING_POLYGON,//绘制模式  多边形
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
            drawingModes:[
                BMAP_DRAWING_POLYGON
            ]
        },
        polygonOptions: styleOptionsDrawing //多边形的样式
    });
};

/**
 * 设置当前ip所在城市
 */
var setCity = function(){
    var cityCenter = function(result){
        var cityName = result.name;
        // map.centerAndZoom(cityName, 15);
        map.setCenter(cityName);
    };
    var myCity = new BMap.LocalCity();
    myCity.get(cityCenter);
};

/**
 * 绘图时样式
 * @type {{strokeColor: string, fillColor: string, strokeWeight: number, strokeOpacity: number, fillOpacity: number, strokeStyle: string}}
 */
var styleOptionsDrawing = {
    strokeColor:"#0b8dda",    //边线颜色。
    fillColor:"#5db6ea",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'dashed' //边线的样式，solid或dashed。
};

/**
 * 展示样式
 * @type {{strokeColor: string, fillColor: string, strokeWeight: number, strokeOpacity: number, fillOpacity: number, strokeStyle: string}}
 */
var styleOptionsShow = {
    strokeColor:"#0b8dda",    //边线颜色。
    fillColor:"#5db6ea",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
};

/**
 * 绘图完成时
 * @param e
 */
//var overlays = new Array();
var overlaycomplete = function(e){
    map.removeOverlay(e.overlay);
};
var manualFenceInfo = new Array();
var polygoncomplete = function(overlay){
    manualFenceInfo.length=0;
    var points = overlay.getPath();
    for(var i=0;i<points.length;i++){
        manualFenceInfo.push( new Array(points[i].lng, points[i].lat) );
    }
    //设置参数-围栏数据
    operateParam.drawData = JSON.stringify(manualFenceInfo);
    if(operateParam.fenceId){
        updateFence(operateParam)
    }else if(!operateParam.fenceId&&operateParam.fenceName){
        addFence(operateParam)
    }
    showElecFenceVal(manualFenceInfo);
    operateParam={};
};

/**
 * 新增围栏
 */
var addFence = function(params){
    IOT.showOverlay('保存中，请稍等...');
    IOT.getServerData(URI.RENT.TRACKING.ELETIC_RANGE.ADD, params, (ret) => {
        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
        IOT.hideOverlay();
        if (ret && ret.code === 200) {
            IOT.tips('保存成功！', 'success');
            layer.closeAll();
            titleArr.length =0;
            titleList.length =0;
            M.Table.refresh.setRange();
        } else {
            IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
        }
    });
};

/**
 * 修改围栏
 */
var updateFence = function(params){
    IOT.showOverlay('更新中，请稍等...');
    IOT.getServerData(URI.RENT.TRACKING.ELETIC_RANGE.MODIFY, params, (ret) => {
        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
        IOT.hideOverlay();
        if (ret && ret.code === 200) {
            IOT.tips('更新成功！', 'success');
            layer.closeAll();
            titleArr.length =0;
            titleList.length =0;
            M.Table.refresh.setRange();
        } else {
            IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
        }
    });
};

/**
 * 删除围栏
 */
var deleteFence = function(params){
    IOT.showOverlay('删除中，请稍等...');
    IOT.getServerData(URI.RENT.TRACKING.ELETIC_RANGE.DELETE, params, (ret) => {
        IOT.tips(ret.msg || '操作失败，请重试！', 'error', 1000, null);
        IOT.hideOverlay();
        if (ret && ret.code === 200) {
            IOT.tips('删除成功！', 'success');
            layer.closeAll();
            titleArr.length =0;
            titleList.length =0;
            M.Table.refresh.setRange();
            clearMap();

        } else {
            IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
        }
    });
};

/**
 * 显示地图中“电子围栏”
 */
function showElecFenceVal(distributerange){
    if(jQuery.isArray(distributerange)){
        var posArray = [];
        for(var i=0; i< distributerange.length;i++){
            posArray.push(new BMap.Point(distributerange[i][0], distributerange[i][1]));
        }
        // 页面中显示的多边形
        var polygon = new BMap.Polygon(posArray,styleOptionsShow);
        map.addOverlay(polygon);
        // 将电子围栏显示在地图中间
        map.setViewport(posArray);
    }
}

/**
 * 清除地图上原有覆盖物
 */
var clearMap = function(){
    map.clearOverlays();
};

$(function(){
    initMap();
    setCity();
    $('#set_range').click(function(){
        var rangeTitle = $('#range_title').val();
        if(rangeTitle == ""){
            $('#range_title').css("border-color","orangered");
        }else{
            $('#client_title').text(rangeTitle);
            $('#myModal').modal('hide')
        }
    });
    //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    drawingManager.addEventListener('polygoncomplete', polygoncomplete);
});
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};